package viper.GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import viper.main.MySQLFunctions;
import viper.main.StateManager;
import viper.main.ViperHeader;

/**
 *
 * @author Kevin Sin
 * 
 * Revision number: 1
 * Date created: 1/17/10
 * Date of Last Back-up on SVN: none
 * 
 * <p>This JPanel is used right after the user selects who he wants to call.  
 * Lets the user select the diversity code and the relays to use. 
 */
public class CallSenderSetupPanel extends javax.swing.JPanel {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/** Creates new form LoggedInJPanel */
    public CallSenderSetupPanel() {
        initComponents();
    }
    

    private JButton logoutButton; //Log out button
    private JButton callButton; //Call button
    private JButton backButton; //Back button
    private JLabel jLabel1; //Directions
    private JLabel jLabel2; //Directions
    private JPanel jPanel1; //Directions
    private JRadioButton radioButton232; //(2,3,2) code radio button
    private JRadioButton radioButton364; //(3,6,4) code radio button
    private JRadioButton radioButton101; //(1,0,1) code radio button
    private JRadioButton radioButton111; //(1,1,1) code radio button
    private ButtonGroup buttonGroup; //For the diversity code buttons
    private JScrollPane jScrollPane1; //For displaying possible relays
    
    private ArrayList<Object[]> relaysSelected = 
    	new ArrayList<Object[]>(); //represents the relays the user has selected 
    private ArrayList<Object[]> possibleRelays = 
    	new ArrayList<Object[]>(); //represents the possible relays to use
    	
    private javax.swing.JList jList1; //Displaying relays
    private  DefaultListModel listModel; //Also for relays list

    /** This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {

        logoutButton = new JButton();
        jLabel1 = new JLabel();
        callButton = new JButton();
        backButton = new JButton();
        jLabel2 = new JLabel();
        radioButton232 = new JRadioButton();
        radioButton364 = new JRadioButton();
        radioButton101 = new JRadioButton();
        radioButton111 = new JRadioButton();
        jScrollPane1 = new JScrollPane();
        
        jPanel1 = new JPanel(new GridLayout(0, 1));
        
        buttonGroup = new ButtonGroup();

        logoutButton.setText("Log out");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        callButton.setText("Call >");
        callButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                callButtonActionPerformed(evt);
            }
        });

        backButton.setText("< Back");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Choose the diversity code:");
        jLabel2.setText("and your relays (Hold CTRL for multiple relays):");
        jLabel1.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        jLabel2.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));

        radioButton101.setBackground(Color.WHITE);
        radioButton101.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        radioButton111.setBackground(Color.WHITE);
        radioButton111.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        radioButton232.setBackground(Color.WHITE);
        radioButton232.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        radioButton364.setBackground(Color.WHITE);
        radioButton364.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 16));
        
        radioButton232.setText("(2, 3, 2)");
        radioButton364.setText("(3, 6, 4)");
        radioButton101.setText("(1, 0, 1)");
        radioButton111.setText("(1, 1, 1)");
        radioButton101.setSelected(true);
        
        buttonGroup.add(radioButton101);
        buttonGroup.add(radioButton111);
        buttonGroup.add(radioButton232);
        buttonGroup.add(radioButton364); 

        jScrollPane1.setViewportView(jPanel1);

        listModel = new DefaultListModel();
    	jList1 = new JList(listModel);
    	jList1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jScrollPane1.setViewportView(jList1);
        jList1.setCellRenderer(new IconListRenderer());
        
        //logout button
        JPanel nextPane = new JPanel();
        nextPane.setBackground(Color.WHITE);
        nextPane.setLayout(new BoxLayout(nextPane, BoxLayout.LINE_AXIS));
        nextPane.add(Box.createHorizontalGlue());
        nextPane.add(logoutButton, BorderLayout.LINE_END);
        
        //button group pane
        JPanel directionsPane = new JPanel();
        directionsPane.setBackground(Color.WHITE);
        directionsPane.setLayout(new BoxLayout(directionsPane, BoxLayout.LINE_AXIS));
        directionsPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        directionsPane.add(Box.createHorizontalGlue());
        directionsPane.add(radioButton101);
        directionsPane.add(Box.createHorizontalStrut(30));
        directionsPane.add(radioButton111);
        directionsPane.add(Box.createHorizontalStrut(30));
        directionsPane.add(radioButton232);
        directionsPane.add(Box.createHorizontalStrut(30));
        directionsPane.add(radioButton364, BorderLayout.LINE_END);

        
        //alldirections
        JPanel alldirectionsPane = new JPanel();
        alldirectionsPane.setBackground(Color.WHITE);
        alldirectionsPane.setLayout(new BorderLayout());
        alldirectionsPane.add(Box.createVerticalGlue());
        alldirectionsPane.add(jLabel1, BorderLayout.NORTH);
        alldirectionsPane.add(directionsPane, BorderLayout.CENTER);
        alldirectionsPane.add(jLabel2, BorderLayout.SOUTH);
        
        //scroll panel
        JPanel scrollPanel = new JPanel();
        scrollPanel.setBackground(Color.WHITE);
        scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
        scrollPanel.setBorder(BorderFactory.createEmptyBorder(5, 20, 20, 20));
        scrollPanel.add(jScrollPane1, BorderLayout.CENTER);
        
        //Back and Call
        JPanel buttonPane = new JPanel();
		buttonPane.setBackground(Color.WHITE);
        buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
        buttonPane.add(Box.createHorizontalGlue());
        buttonPane.add(backButton);
        buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPane.add(callButton, BorderLayout.LINE_END);
        
        setLayout(new BorderLayout());
        add(alldirectionsPane, BorderLayout.PAGE_START);
        add(scrollPanel, BorderLayout.CENTER);
        add(buttonPane, BorderLayout.AFTER_LAST_LINE);
    }

    /**
     * @param evt
     * Logout button pressed
     */
    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        StateManager.INSTANCE.logout();
    }                                        

    /**
     * @param evt
     * Call button pressed
     */
    private void callButtonActionPerformed(java.awt.event.ActionEvent evt) {  
    	if(radioButton232.isSelected()) //(2,3,2) code selected, check if 3 relays selected
    	{
    		if(countChecks()==3)
    		{
    			StateManager.INSTANCE.setRelays(relaysSelected);
    			StateManager.INSTANCE.setDiversityCode(ViperHeader.CODE_232);
    			StateManager.INSTANCE.call();
    		}
    		else
    			JOptionPane.showMessageDialog(this, "Please select 3 relays!");
    	}
    	else if(radioButton101.isSelected()) //(1,0,1) code selected, check 0 relays selected
    	{
    		if(countChecks()==0)
    		{
    			StateManager.INSTANCE.setRelays(new ArrayList<Object[]>());
    			StateManager.INSTANCE.setDiversityCode(ViperHeader.CODE_101);
    			StateManager.INSTANCE.call();
    		}
    		else
    			JOptionPane.showMessageDialog(this, "Please select 0 relays!");
    	}
    	else if(radioButton111.isSelected())
    	{
    		if(countChecks()==1)
    		{
    			StateManager.INSTANCE.setRelays(relaysSelected);
    			StateManager.INSTANCE.setDiversityCode(ViperHeader.CODE_111);
    			StateManager.INSTANCE.call();
    		}
    		else
    			JOptionPane.showMessageDialog(this, "Please select 1 relay!");
    	}
    	else //(3, 6, 4) code selected, check if 6 relays selected
    	{
    		if(countChecks()==6)
    		{
    			StateManager.INSTANCE.setRelays(relaysSelected);
    			StateManager.INSTANCE.setDiversityCode(ViperHeader.CODE_364);
    			StateManager.INSTANCE.call();
    		}
    		else
    			JOptionPane.showMessageDialog(this, "Please select 6 relays!");
    	}
        
    }                                 
    
    /**
     * @return number of checkboxes checked
     */
    private int countChecks() {
    	Object[] selectedValues = jList1.getSelectedValues();
    	for(Object selectedValue : selectedValues)
    	{
    		JLabel selectedLabel = (JLabel)selectedValue;
    		String peerString = selectedLabel.getText();
        	String peerIP = peerString.split("---")[1];
        	Object[] possibleRelay = StateManager.INSTANCE.getPeerRowFromIP(peerIP);
        	relaysSelected.add(possibleRelay);
    	}
    	return selectedValues.length;
    }

    /**
     * @param evt
     * Back button pressed
     */
    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	ViperGUI.INSTANCE.changeCard(ViperGUI.LOGGED_IN_CARD);
    }
    
    /**
     * Updates possibleRelays.  Make sure callee is not included.
     */
    private void updatePossibleRelays() {    	
    	possibleRelays = StateManager.INSTANCE.getPeers();
    	for(Object[] peerArray : possibleRelays)
    	{
    		if(((String)(StateManager.INSTANCE.getCalleeArray()[0])).equals((String)(peerArray[0])))
    		{
    			possibleRelays.remove(peerArray);
    			break;
    		}
    	}
    }

    /**
     * Update relays and display relays
     */
    public void update(){
    	updatePossibleRelays();
    	ImageIcon icon = null;
		listModel.clear();
		for(Object[] peer : StateManager.INSTANCE.getPeers())
		{
			String peerString = peer[1] + "---" + peer[0];
			if(peer[2].equals(MySQLFunctions.STATUS_FREE))
			{
				icon = new ImageIcon("images/green_phone.gif");
			}
			else if(peer[2].equals(MySQLFunctions.STATUS_BUSY))
			{
				icon = new ImageIcon("images/busy.gif");
			}
			else if(peer[2].equals(MySQLFunctions.STATUS_BAD_RELAY))
			{
				icon = new ImageIcon("images/relay.gif");
			}
			JLabel label = new JLabel(peerString);
			label.setIcon(icon);
			listModel.addElement(label);
		}
		jList1.repaint();
    }
}

